package com.zhengshang.api.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.zhengshang.api.domain.*;
import com.zhengshang.api.service.*;
import com.zhengshang.api.task.payorder.PayOrderCollection;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.CommonConstants;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.constant.app.PhoneBillConstants;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysRole;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.pay.alipay.AlipayService;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.common.utils.uuid.IdUtils;
import com.zhengshang.security.service.SysPermissionService;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.domain.SysConfig;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysUserService;
/*import fulu.sup.open.api.core.MethodConst;
import fulu.sup.open.api.sdk.DefaultOpenApiClient;*/
import com.zhengshang.third.phone.PhoneAreaUtils;
import com.zhengshang.third.wikeyun.WikeyunApi;
import com.zhengshang.third.wikeyun.WikeyunUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 首页Controller
 *
 * @author zhengshang
 * @date 2021-03-09
 */
@Api(tags = "支付宝支付")
@RestController
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private IAppPayRecordService appPayRecordService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppBillProductService appBillProductService;
    @Autowired
    private IAppBillRecordService appBillRecordService;
    @Autowired
    private IAppBalanceRecordService appBalanceRecordService;
    @Autowired
    private IAppBillRefundRecordService appBillRefundRecordService;
    @Autowired
    private IAppThirdColumnService appThirdColumnService;
    @Autowired
    private WikeyunUtils wikeyunUtils;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private PhoneAreaUtils phoneAreaUtils;
    @Autowired
    private IAppOilcardService appOilcardService;

    private final String success = "success";

    private final String fail = "fail";

    /**
     * @throws
     * @title 获取购买星级会员签名
     * @description
     * @author admin
     * @updateTime 2021/3/25 15:50
     */
    @ApiOperation(value = "获取购买星级会员签名")
    @RepeatSubmit
    @PostMapping("/getMemSign")
    public AjaxResult getMemSign(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            List<SysRole> roleList = loginAppUser.getAppUser().getRoles();
            for (SysRole sysRole : roleList) {
                if ("mem_vip".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过VIP会员，请勿重复购买");
                }
                if ("mem_member".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过星级会员，无需重复购买，可以升级到VIP会员");
                }
            }

            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_MEMBER);
            String result = alipayService.getCertificateSign("星级会员可解锁优惠加油和广告赚钱功能", "购买星级会员", AppConstant.MEM_MEMBER, orderNum, CommonConstants.getAliNotifyUrl());
//            JSONObject resultObj = analysisResult(result);
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("1");
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_MEMBER);
            appPayRecord.setPayMoney(new BigDecimal(AppConstant.MEM_MEMBER));
            appPayRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appPayRecord.setParam(result);
            appPayRecord.setStatus("10");
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);
            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            return AjaxResult.success("购买成功", result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AjaxResult.error("购买失败");
        }
    }

    /**
     * @throws
     * @title 获取购买VIP会员签名
     * @description
     * @author admin
     * @updateTime 2021/3/25 15:50
     */
    @ApiOperation(value = "获取购买VIP会员签名")
    @RepeatSubmit
    @PostMapping("/getVIPSign")
    public AjaxResult getVIPSign(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            List<SysRole> roleList = loginAppUser.getAppUser().getRoles();
            for (SysRole sysRole : roleList) {
                if ("mem_vip".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过VIP会员，请勿重复购买");
                }
            }

            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_VIP);
            String result = alipayService.getCertificateSign("VIP会员可解锁APP所有功能", "购买VIP会员", AppConstant.MEM_VIP, orderNum, CommonConstants.getAliNotifyUrl());
//            JSONObject resultObj = analysisResult(result);
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("1");
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_VIP);
            appPayRecord.setPayMoney(new BigDecimal(AppConstant.MEM_VIP));
            appPayRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appPayRecord.setParam(result);
            appPayRecord.setStatus("10");
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);
            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            return AjaxResult.success("获取成功", result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }

    @ApiOperation(value = "获取话/电/水/燃气费充值签名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号/户号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "billId", value = "商品ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "areaName", value = "所属城市", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fast", value = "是否快充（1：快速 0：慢）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "充值类型（1慢充，2快充,4电费 5水费 6燃气费）", required = true, dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/getBillSign")
    public AjaxResult getBillSign(
            @RequestParam String phone,
            @RequestParam Long billId,
            @RequestParam(required = false) String areaName,
            @RequestParam(required = false, defaultValue = "0") Integer fast,
            @RequestParam String type,
            @RequestParam(required = false, defaultValue = "1") String productType,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            if (org.apache.commons.lang3.StringUtils.isBlank(phone) || org.apache.commons.lang3.StringUtils.isBlank(type) || billId == null || billId.longValue() <= 0) {
                return AjaxResult.error("参数异常");
            }
            //话费充值
            if (type.equals("1") || type.equals("2")) {
                if(productType.equals("1")||productType.equals("2")){
                    AppPhoneArea phoneInfo = phoneAreaUtils.getPhoneInfo(phone);
                    if (StringUtils.isNotNull(phoneInfo)) {
                        Integer isTransfer = phoneInfo.getIsTransfer();
                        if (isTransfer == 1) {
                            return AjaxResult.error("本手机号是携号转网号码，暂不支持充值，请更换其他手机号充值");
                        }
                    }
                }
            }
            if (StringUtils.isNotNull(fast) && fast.equals(1)) {
                String beginDate = DateUtils.getDate() + " " + "08:00";
                String endDate = DateUtils.getDate() + " " + "22:00";
                Date now = DateUtils.getNowDate();
                if (now.after(DateUtils.parseDate(endDate)) || now.before(DateUtils.parseDate(beginDate))) {
                    //return AjaxResult.error(402, "快冲时间段为08:00-22:00，很抱歉！其他时间不能充值。");
                }
                return AjaxResult.error(402, "系统暂时不支持快速充值,请使用特惠慢充。");
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            Long userId = loginAppUser.getAppUser().getUserId();
            AppBillProduct appBillProduct = appBillProductService.selectAppBillProductById(billId);
            String check = appBillProduct.getRemark();
            SysUser user = userService.selectUserById(userId);
            String appMemberType = user.getAppMemberType();
            System.out.println("check:" + check);
            System.out.println("appMemberType:" + appMemberType);
            if (ObjectUtils.isNotEmpty(check) && appMemberType.equals("2") && check.equals("110")) {
                //检测特殊商品充值
                AppBillRecord appBillRecord = new AppBillRecord();
                appBillRecord.setUserId(userId);
                appBillRecord.setRemark("110");
                String date = DateUtils.getMonth();
                appBillRecord.setSearchValue(date);
                List<AppBillRecord> appBillRecordList = appBillRecordService.queryAppBillRecordList(appBillRecord);
                if (ObjectUtils.isNotEmpty(appBillRecordList)) {
                    return AjaxResult.error(402, "您已体验过该活动，请购买vip会员可享受充值权利");
                }
            }


            String prefix = AppConstant.ORDERNUM_PREFIX_BILL;
            if ("4".equals(productType) || "5".equals(productType) || "6".equals(productType)) {
                prefix = AppConstant.ORDERNUM_PREFIX_PC;
            }
            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_BILL);
            BigDecimal payMoney = appBillProduct.getMoney();
            String productId = "";
            if ("1".equals(type) && ("4".equals(productType) || "5".equals(productType) || "6".equals(productType) || "1".equals(productType) || "2".equals(productType))) {
                //移动
                payMoney = appBillProduct.getMobileMoneyPrice();
                productId = appBillProduct.getMobileFuluProductId();
            } else if ("2".equals(type)) {
                //电信
                payMoney = appBillProduct.getTelecomMoneyPrice();
                productId = appBillProduct.getTelecomFuluProductId();
            } else if ("3".equals(type)) {
                //联通
                payMoney = appBillProduct.getUnicomMoneyPrice();
                productId = appBillProduct.getUnicomFuluProductId();
            } else {
                return AjaxResult.error("参数异常!");
            }
            String title = "话费充值";
            if (productType.equals("4")) {
                title = "电费充值";
            }
            if (productType.equals("5")) {
                title = "水费充值";
            }
            if (productType.equals("6")) {
                title = "燃气费充值";
            }


            String result = alipayService.getCertificateSign("商品充值", title, payMoney.doubleValue() + "", orderNum, CommonConstants.getAliNotifyUrl());
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("1");
            appPayRecord.setAreaName(areaName);
            appPayRecord.setFast(fast);
            appPayRecord.setBuyType(prefix);
            appPayRecord.setPayMoney(payMoney);
            appPayRecord.setUserId(userId);
            appPayRecord.setParam(result);
            appPayRecord.setStatus("10");
            appPayRecord.setRechargeState("0");
            appPayRecord.setProductType(Integer.parseInt(productType));
            appPayRecord.setPhone(phone);
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            JSONObject remark = new JSONObject();
            remark.put("billType", type);
            remark.put("productId", productId);
            remark.put("areaName", areaName);
            remark.put("productType", Integer.parseInt(productType));
            remark.put("fast", fast);
            remark.put("money", appBillProduct.getMoney());
            String tag = appBillProduct.getRemark();
            if (ObjectUtils.isNotEmpty(tag) && (tag.equals("110") || tag.equals("100"))) {
                remark.put("tag", tag);
            }
            appPayRecord.setRemark(remark.toJSONString());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);

            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            return AjaxResult.success("获取成功", result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }


    @ApiOperation(value = "获取油卡充值签名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oilcardId", value = "手机号/户号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "billId", value = "商品ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/getOilcardSign")
    public AjaxResult getOilcardSign(@RequestParam Long oilcardId, @RequestParam Long billId, @RequestParam(required = false, defaultValue = "7") String type, HttpServletRequest request) {
        try {
            if (!"7".equals(type)) {
                return AjaxResult.error("该接口只支持油卡充值");
            }
            if (StringUtils.isNull(oilcardId)) {
                return AjaxResult.error("缺少参数");
            }
            AppOilcard appOilcard = appOilcardService.selectAppOilcardById(oilcardId);
            if (StringUtils.isNull(appOilcard)) {
                return AjaxResult.error("油卡不存在");
            }
            if (StringUtils.isNull(billId)) {
                return AjaxResult.error("缺少参数");
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            Long userId = loginAppUser.getAppUser().getUserId();
            AppBillProduct appBillProduct = appBillProductService.selectAppBillProductById(billId);
            SysUser user = userService.selectUserById(userId);
            String appMemberType = user.getAppMemberType();
            System.out.println("appMemberType:" + appMemberType);
            if (!appMemberType.equals("3")) {
                return AjaxResult.error("只有VIP用户才能享受");
            }
            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_OILCARD);
            BigDecimal payMoney = appBillProduct.getMobileMoneyPrice();
            String title = "油卡充值";
            String result = alipayService.getCertificateSign("商品充值", title, payMoney.doubleValue() + "", orderNum, CommonConstants.getAliNotifyUrl());
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("1");
            appPayRecord.setFast(0);
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_OILCARD);
            appPayRecord.setPayMoney(payMoney);
            appPayRecord.setUserId(userId);
            appPayRecord.setParam(result);
            appPayRecord.setBillId(billId);
            appPayRecord.setOilcardId(oilcardId);
            appPayRecord.setStatus("10");
            appPayRecord.setRechargeState("0");
            appPayRecord.setProductType(Integer.parseInt(type));
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            JSONObject remark = new JSONObject();
            remark.put("productType", Integer.parseInt(type));
            remark.put("money", appBillProduct.getMoney());
            remark.put("oilcardId", oilcardId);
            remark.put("billId", billId);
            String tag = appBillProduct.getRemark();
            if (ObjectUtils.isNotEmpty(tag) && (tag.equals("110") || tag.equals("100"))) {
                remark.put("tag", tag);
            }
            appPayRecord.setRemark(remark.toJSONString());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);

            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            Long payId = appPayRecord.getRecordId();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("payId", payId);
            resultMap.put("result", result);
            return AjaxResult.success("获取成功", resultMap);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }

    @ApiOperation(value = "获取影视,音乐,在线教育,商品券充值签名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "充值账号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "billId", value = "所属商品", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fast", value = "是否快充（1：快速 0：慢）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "充值类型（11影视会员,12音乐会员,13在线教育,14肯德基,15麦当劳）", required = true, dataType = "String", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/getWiKeYunProductSign")
    public AjaxResult getWiKeYunProductSign(@RequestParam String account, @RequestParam Long billId, @RequestParam String type, HttpServletRequest request) {
        try {
            List<String> productTypes = Lists.newArrayList();
            productTypes.add("11");
            productTypes.add("12");
            productTypes.add("13");
            if (com.zhengshang.common.utils.StringUtils.isEmpty(account) && productTypes.contains(type)) {
                return AjaxResult.error("充值账号不能为空");
            }
            productTypes.add("14");
            productTypes.add("15");
            productTypes.add("16");
            productTypes.add("17");
            productTypes.add("18");
            productTypes.add("19");
            if (!productTypes.contains(type)) {
                return AjaxResult.error("充值类型有误");
            }
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            Long userId = loginAppUser.getAppUser().getUserId();
            AppBillProduct appBillProduct = appBillProductService.selectAppBillProductById(billId);
            if (StringUtils.isNull(appBillProduct)) {
                return AjaxResult.error("该产品不存在");
            }
            Long thirdColumnId = appBillProduct.getThirdColumnId();
            if (StringUtils.isNull(thirdColumnId)) {
                return AjaxResult.error("产品信息不完善");
            }
            AppThirdColumn appThirdColumn = appThirdColumnService.selectAppThirdColumnById(thirdColumnId);
            if (StringUtils.isNull(appThirdColumn)) {
                return AjaxResult.error("产品信息不完善");
            }
            Integer productType = appBillProduct.getProductType();
            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_THIRD);
            BigDecimal payMoney = appBillProduct.getMobileMoneyPrice();
            String title = "订单支付";
            String result = alipayService.getCertificateSign("商品充值", title, payMoney.doubleValue() + "", orderNum, CommonConstants.getAliNotifyUrl());
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("1");
            appPayRecord.setBillId(billId);
            appPayRecord.setFast(1);
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_THIRD);
            appPayRecord.setPayMoney(payMoney);
            appPayRecord.setUserId(userId);
            appPayRecord.setParam(result);
            appPayRecord.setStatus("10");
            appPayRecord.setRechargeState("0");
            appPayRecord.setProductType(productType);
            appPayRecord.setPhone(account);
            appPayRecord.setBillId(billId);
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            JSONObject remark = new JSONObject();
            remark.put("billType", type);
            remark.put("productId", billId);
            remark.put("thirdServerId", appThirdColumn.getWikeyunServerid());
            remark.put("thirdProductId", appBillProduct.getMobileFuluProductId());
            remark.put("productType", productType);
            remark.put("fast", 1);
            remark.put("money", appBillProduct.getMoney());
            String tag = appBillProduct.getRemark();
            if (ObjectUtils.isNotEmpty(tag) && (tag.equals("110") || tag.equals("100"))) {
                remark.put("tag", tag);
            }
            appPayRecord.setRemark(remark.toJSONString());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);

            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            Long payId = appPayRecord.getRecordId();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("payId", payId);
            resultMap.put("result", result);
            return AjaxResult.success("获取成功", resultMap);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }


    /**
     * 支付宝回调
     */
    @PostMapping("/gateway")
    public String gateway(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> result = alipayService.asyn(request);
            String tradeStatus = result.get("trade_status");
            if (StringUtils.isNotBlank(tradeStatus) && ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus) || "TRADE_FINISHED".equalsIgnoreCase(tradeStatus))) {
                String orderNum = result.get("out_trade_no");
                AppPayRecord appPayRecord = appPayRecordService.selectAppPayRecordByOrderNum(orderNum);
                if (appPayRecord != null) {
                    appPayRecord.setStatus("20");
                    appPayRecord.setTradeNo(result.get("trade_no"));
                    appPayRecord.setBuyerUserId(result.get("buyer_id"));
                    appPayRecord.setCallbackData(result.get("data"));
                    appPayRecordService.updateAppPayRecord(appPayRecord);
                    PayOrderCollection.remove(orderNum);

                    LoginAppUser loginAppUser = tokenService.getLoginAppUser(appPayRecord.getUserId());

                    switch (appPayRecord.getBuyType()) {
                        //购买星级会员
                        case AppConstant.ORDERNUM_PREFIX_MEMBER:
                            loginAppUser.getAppUser().setAppMemberType("2");
                            loginAppUser = userService.updateRole(loginAppUser, "mem_member");
                            break;
                        //购买VIP
                        case AppConstant.ORDERNUM_PREFIX_VIP:
                            loginAppUser.getAppUser().setAppMemberType("3");
                            loginAppUser = userService.updateRole(loginAppUser, "mem_vip");
                            userService.thawCommission(loginAppUser.getAppUser());//解冻被冻结的佣金
                            break;
                        case AppConstant.ORDERNUM_PREFIX_BILL:
                            return gatewayBill(appPayRecord, loginAppUser);
                        case AppConstant.ORDERNUM_PREFIX_PC:
                            return gatewayBill(appPayRecord, loginAppUser);
                        //充值油卡
                        case AppConstant.ORDERNUM_PREFIX_OILCARD:
                            return gatewayOilcard(appPayRecord, loginAppUser);
                        //购买微客云产品
                        case AppConstant.ORDERNUM_PREFIX_THIRD:
                            return gatewayWiKeYun(appPayRecord, loginAppUser);
                    }
                    //更新上级及上上级用户余额
                    userService.buyMember(
                            loginAppUser.getAppUser(),
                            loginAppUser.getAppUser().getUpUserId(),
                            appPayRecord.getBuyType(),
                            new AppDefaultParam(configService.selectConfigByKey("app.buyvip.up.bonus"), configService.selectConfigByKey("app.buyvip.upup.bonus"), configService.selectConfigByKey("app.buymem.up.bonus"))
                    );
                    loginAppUser.setPermissions(permissionService.getMenuPermission(loginAppUser.getAppUser()));
                    tokenService.refreshToken(loginAppUser);
                    return success;
                }
            }
        } catch (AlipayApiException e) {
            logger.error("<alipay.gateway>支付宝回调结果异常,异常原因{}", e.getMessage());
            e.printStackTrace();
        }
        return fail;
    }

    /**
     * 油卡充值回调
     *
     * @param appPayRecord
     * @param loginAppUser
     * @return
     */
    private String gatewayOilcard(AppPayRecord appPayRecord, LoginAppUser loginAppUser) {
        try {
            JSONObject remarkObj = JSONObject.parseObject(appPayRecord.getRemark());
            String billId = remarkObj.getString("billId");
            String oilcardId = remarkObj.getString("oilcardId");
            Integer productType = remarkObj.getInteger("productType");
            //充值记录
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByPayId(appPayRecord.getRecordId());
            if (appBillRecord == null) {
                appBillRecord = new AppBillRecord();
                appBillRecord.setUserId(appPayRecord.getUserId());
                appBillRecord.setMoney(remarkObj.getBigDecimal("money"));
                appBillRecord.setOrderPrice(appPayRecord.getPayMoney());
                appBillRecord.setFast(1);
                appBillRecord.setProductType(productType);
                appBillRecord.setPhone(oilcardId);
                appBillRecord.setPayId(appPayRecord.getRecordId());
                appBillRecord.setProductId(billId);
                appBillRecord.setOrderState("1");
                appBillRecord.setOrderNum(appPayRecord.getOrderNum());
                appBillRecord.setCreateBy(appPayRecord.getCreateBy());
                appBillRecordService.insertAppBillRecord(appBillRecord);
            }
            return success;
        } catch (Exception e) {
            logger.error("<alipay.gatewayBill>支付宝回调结果异常,异常原因{}", e.getMessage());
            e.printStackTrace();
        }
        return fail;
    }


    /**
     * 微客云商品购买回调
     *
     * @param appPayRecord
     * @param loginAppUser
     * @return
     */
    private String gatewayWiKeYun(AppPayRecord appPayRecord, LoginAppUser loginAppUser) {
        try {
            JSONObject remarkObj = JSONObject.parseObject(appPayRecord.getRemark());
            Integer productType = remarkObj.getInteger("productType");
            //微客云权益Id
            String thirdServerId = remarkObj.getString("thirdServerId");
            //微客云规格Id
            String thirdProductId = remarkObj.getString("thirdProductId");
            //充值记录
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByPayId(appPayRecord.getRecordId());
            if (appBillRecord == null) {
                appBillRecord = new AppBillRecord();
                appBillRecord.setUserId(appPayRecord.getUserId());
                appBillRecord.setMoney(remarkObj.getBigDecimal("money"));
                appBillRecord.setOrderPrice(appPayRecord.getPayMoney());
                appBillRecord.setFast(1);
                appBillRecord.setProductType(productType);
                appBillRecord.setPhone(appPayRecord.getPhone());
                appBillRecord.setPayId(appPayRecord.getRecordId());
                appBillRecord.setProductId(thirdProductId);
                appBillRecord.setOrderState("1");
                appBillRecord.setOrderNum(appPayRecord.getOrderNum());
                appBillRecord.setCreateBy(appPayRecord.getCreateBy());
                appBillRecordService.insertAppBillRecord(appBillRecord);
            }
            String rechargeState = appPayRecord.getRechargeState();
            if ("0".equals(rechargeState)) {
                String domainUrl = sysConfigService.selectConfigByKey("sys.domain.name") + "api/wikeyun/notify/wiKeYunServerOrder";
                //回调成功去调充值接口
                TreeMap<String, Object> params = new TreeMap<>();
                params.put("store_id", wikeyunUtils.storeId);
                params.put("id", thirdServerId);
                params.put("spec_id", thirdProductId);
                params.put("account", appBillRecord.getPhone());
                params.put("client_type", "app");
                params.put("cms_order_num", appPayRecord.getOrderNum());
                params.put("notify_url", domainUrl);
                String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.quanyiSaveOrder);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.getString("code");
                //获取数据
                if ("0000".equals(code)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    String orderNo = data.getString("order_no");
                    appBillRecord.setFuluOrderId(orderNo);
                    appBillRecordService.updateAppBillRecord(appBillRecord);
                    appPayRecord.setRechargeState("1");
                    appPayRecordService.updateAppPayRecord(appPayRecord);
                } else {
                    appPayRecordService.refund(appPayRecord);
                }
            }
            return success;
        } catch (Exception e) {
            logger.error("<alipay.gatewayBill>支付宝回调结果异常,异常原因{}", e.getMessage());
            e.printStackTrace();
        }
        return fail;
    }

    /**
     * 话费充值回调
     *
     * @return
     */
    public String gatewayBill(AppPayRecord appPayRecord, LoginAppUser loginAppUser) {
        try {
            JSONObject remarkObj = JSONObject.parseObject(appPayRecord.getRemark());
            String productId = remarkObj.getString("productId");
            String areaName = remarkObj.getString("areaName");
            Integer productType = remarkObj.getInteger("productType");
            Integer fast = remarkObj.getInteger("fast");
            //是否是优惠券充值
            Integer tag = remarkObj.getInteger("tag");

            //话费充值记录
            AppBillRecord appBillRecord = appBillRecordService.selectAppBillRecordByPayId(appPayRecord.getRecordId());
            if (appBillRecord == null) {
                appBillRecord = new AppBillRecord();
                appBillRecord.setUserId(appPayRecord.getUserId());
                appBillRecord.setMoney(remarkObj.getBigDecimal("money"));
                appBillRecord.setOrderPrice(appPayRecord.getPayMoney());
                appBillRecord.setFast(fast);
                appBillRecord.setProductType(productType);
                appBillRecord.setAreaName(areaName);
                appBillRecord.setPhone(appPayRecord.getPhone());
                appBillRecord.setPayId(appPayRecord.getRecordId());
                appBillRecord.setProductId(productId);
                appBillRecord.setOrderState("1");
                appBillRecord.setOrderNum(appPayRecord.getOrderNum());
                appBillRecord.setCreateBy(appPayRecord.getCreateBy());

                //更新优惠券数量
                if (ObjectUtils.isNotEmpty(tag)) {
                    if (tag.equals(100)) {
                        //话费
                        SysUser sysUser = userService.selectUserById(loginAppUser.getAppUser().getUserId());
                        Integer couponCount = sysUser.getCouponCount();
                        if (ObjectUtils.isNotEmpty(couponCount) && couponCount > 0) {
                            couponCount = couponCount - 1;
                        }
                        sysUser.setCouponCount(couponCount);
                        userService.updateUser(sysUser);
                    }
                    appBillRecord.setRemark(tag.toString());
                }
                appBillRecordService.insertAppBillRecord(appBillRecord);
            }


            //充值
//            DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTPS, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_DIRECT_ORDER_ADD);
//            JSONObject bizContent = new JSONObject();
//            bizContent.put("charge_phone", appPayRecord.getPhone());
//            bizContent.put("charge_value", appBillRecord.getMoney().intValue());
//            bizContent.put("customer_order_no", appPayRecord.getOrderNum());
//            client.setBizContent(bizContent.toJSONString());
//           JSONObject billResultObj = JSONObject.parseObject(client.excute());
//
//            bizContent.put("charge_account", appPayRecord.getPhone());
//            bizContent.put("buy_num", "1");
//           bizContent.put("product_id", productId);
//            bizContent.put("customer_order_no", appPayRecord.getOrderNum());
//            client.setBizContent(bizContent.toJSONString());
//           JSONObject billResultObj = JSONObject.parseObject(client.excute());
//            JSONObject billResultObj = JSONObject.parseObject(null);
//
//            if (billResultObj.getIntValue("code") == 0) {
//                //此时为订单提交成功，并未充值成功
//               appBillRecord.setFuluOrderId(billResultObj.getString("order_id"));
//
//                logger.info("<alipay.gateway>用户<{}>为<{}>充值{}元话费成功", appPayRecord.getUserId(), appPayRecord.getPhone(), appPayRecord.getPayMoney());
//            } else {
//                appBillRecord.setChargeFinishTime(DateUtils.getNowDate());
//                logger.error("<alipay.gateway>话费充值失败：{}", billResultObj);
//
//                //是否立即退款
//                String refundNow = configService.selectConfigByKey("app.pay.refund.now");
//                if ("1".equals(refundNow)) {
//                    //退款
//                    refund(appPayRecord, appBillRecord,"话费充值失败");
//                }
//           }

            //appBillRecordService.updateAppBillRecord(appBillRecord);

            return success;
        } catch (Exception e) {
            logger.error("<alipay.gatewayBill>支付宝回调结果异常,异常原因{}", e.getMessage());
            e.printStackTrace();
        }
        return fail;
    }

    private synchronized JSONObject analysisResult(String result) {
        JSONObject returnObj = new JSONObject();
        if (StringUtils.isNotBlank(result)) {
            String[] values = result.split("&");
            for (String str : values) {
                String[] keyVal = str.split("=");
                String key = keyVal[0];
                String value = keyVal[1];
                try {
                    value = java.net.URLDecoder.decode(value.toString(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if ("biz_content".equals(key)) {
                    returnObj.put(key, JSONObject.parseObject(value));
                } else {
                    returnObj.put(key, value);
                }
//                logger.info("<key=value>：" + str);
            }
        }
        return returnObj;
    }

    /**
     * 退款
     *
     * @param appPayRecord
     * @param appBillRecord
     */
    public void refund(AppPayRecord appPayRecord, AppBillRecord appBillRecord, String refundReason) {
        try {

            String refundOrderNum = appPayRecord.getOrderNum() + "TK";
            String result = alipayService.alipayRefund(appPayRecord.getOrderNum(), appPayRecord.getPayMoney().toString(), refundReason, refundOrderNum);
            JSONObject object = JSONObject.parseObject(result);
            JSONObject alipayTradeRefundResponse = object.getJSONObject("alipay_trade_refund_response");
            if ("10000".equals(alipayTradeRefundResponse.getString("code"))) {
                //退款记录
                AppBillRefundRecord appBillRefundRecord = new AppBillRefundRecord();
                appBillRefundRecord.setUserId(appBillRecord.getUserId());
                appBillRefundRecord.setBillId(appBillRecord.getRecordId());
                appBillRefundRecord.setOrderNum(appBillRecord.getOrderNum());
                appBillRefundRecord.setRefundOrderNum(refundOrderNum);
                appBillRefundRecord.setRefundType(appPayRecord.getPayType());
                appBillRefundRecord.setRefundFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setTotalFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setResult(result);
                appBillRefundRecord.setCreateBy(appBillRecord.getCreateBy());
                appBillRefundRecordService.insertAppBillRefundRecord(appBillRefundRecord);
                appBillRecord.setOrderState("5");
                appBillRecordService.updateAppBillRecord(appBillRecord);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @throws
     * @title 退款
     * @description
     * @author admin
     * @updateTime 2021/3/25 15:50
     */
    @PreAuthorize("@ss.hasPermi('app:user:alipay:refund')")
    @PostMapping("/refund")
    public AjaxResult refund(
            @RequestParam String outTradeNo,
            @RequestParam String refundAmount,
            @RequestParam String refundReason,
            @RequestParam String outRequestNo,
            HttpServletRequest request, HttpServletResponse response) {
        try {

            String result = alipayService.alipayRefund(outTradeNo, refundAmount, refundReason, outRequestNo);
            return AjaxResult.success("获取成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }


}
